package com.example.myapplication;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.myapplication.db.DBManager;

public class AddTeacherCourseActivity extends AppCompatActivity {
    private EditText editTextTeacherName;
    private EditText editTextTeacherInfo;
    private EditText editTextCourseName;
    private Button buttonSubmit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_teacher_course);
        setTitle("录入老师任课");

        // 启用返回按钮
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

        // 初始化视图
        editTextTeacherName = findViewById(R.id.editTextTeacherName);
        editTextTeacherInfo = findViewById(R.id.editTextTeacherInfo);
        editTextCourseName = findViewById(R.id.editTextCourseName);
        buttonSubmit = findViewById(R.id.buttonSubmitTeacherCourse);

        // 设置提交按钮点击事件
        buttonSubmit.setOnClickListener(v -> saveTeacherAndCourse());
    }

    private void saveTeacherAndCourse() {
        // 获取输入内容
        String teacherName = editTextTeacherName.getText().toString().trim();
        String teacherInfo = editTextTeacherInfo.getText().toString().trim();
        String courseName = editTextCourseName.getText().toString().trim();

        // 验证输入
        if (teacherName.isEmpty()) {
            Toast.makeText(this, "请输入老师姓名", Toast.LENGTH_SHORT).show();
            return;
        }
        if (courseName.isEmpty()) {
            Toast.makeText(this, "请输入课程名称", Toast.LENGTH_SHORT).show();
            return;
        }

        // 保存到数据库
        new Thread(() -> {
            DBManager dbManager = new DBManager(this);
            boolean success = dbManager.addTeacherAndCourse(teacherName, teacherInfo, courseName);

            // 在主线程显示结果
            runOnUiThread(() -> {
                if (success) {
                    Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
                    finish();
                } else {
                    Toast.makeText(this, "保存失败，请重试", Toast.LENGTH_SHORT).show();
                }
            });
        }).start();
    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }
}
